﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadDemo
{

    public class Program
    {
        public static EventWaitHandle oddFlag = new EventWaitHandle(false, EventResetMode.AutoReset);
        public static EventWaitHandle evenFlag = new EventWaitHandle(false, EventResetMode.AutoReset);
        public static void Main(string[] args)
        {
            Thread.Sleep(1000);//主线程暂停1秒
            Thread npt = new Thread(new ThreadStart(NonParaThread));
            npt.Start();
            Thread wpt = new Thread(new ParameterizedThreadStart(WithParaThread));
            wpt.Start("带参数的线程");
            Thread.Sleep(1000);//主线程暂停1秒
            // 交替输出100以内奇数偶数
            Thread odd = new Thread(new ThreadStart(Odd));
            odd.Start();
            Thread even = new Thread(new ThreadStart(Even));
            even.Start();
            Console.ReadKey();
        }
        //输出奇数
        private static void Odd()
        {
            for (int i = 1; i < 100; i=i+2)
            {
                Console.WriteLine("奇数:"+i);
                evenFlag.Set();
                oddFlag.WaitOne();
            }
            evenFlag.Set();
        }
        //输出偶数
        private static void Even()
        {
            evenFlag.WaitOne();
            for (int i = 0; i <=100; i = i + 2)
            {
                Console.WriteLine("偶数:" + i);
                oddFlag.Set();
                evenFlag.WaitOne();
            }
            oddFlag.Set();
        }
        private static void NonParaThread() {
            Console.WriteLine("我是不带参数的线程");
            Thread.Sleep(1000);//NonParaThread线程暂停1秒
            Console.WriteLine("我是不带参数的线程，执行完毕");
        }
        private static void WithParaThread(Object obj)
        {
            Console.WriteLine(obj);
            Console.WriteLine("我是"+ obj +"，执行完毕");
        }
    }
}
